package com.wrb.customer.utils;

import com.wrb.customer.redis.RedisService;
import com.wrb.customer.redis.keymodel.CustomerKey;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

@Slf4j
@Component
public class JWTUtils {

	private final static String base64Secret = "wrb_summary_2019";

	@Autowired
	private RedisService redisService;

	@Autowired
	private static RedisService staticRedisService;

	@PostConstruct
	private void init() {
		staticRedisService = redisService;
	}

	public static String checkToken(String token) {
		Claims claims = JWTUtils.parseJWT(token);
		if (claims == null) {
			return "";
		}
		String parseUser = (String) claims.get("customerId");
		if (parseUser == null) {
			return "";
		}
		return parseUser;
	}

	/**
	 * 解析jwt
	 */
	private static Claims parseJWT(String jsonWebToken) {
		try {
			return Jwts.parser()
					.setSigningKey(DatatypeConverter.parseBase64Binary(base64Secret))
					.parseClaimsJws(jsonWebToken).getBody();
		} catch (Exception ex) {
			return null;
		}
	}

	/**
	 * 构建会员 jwt 并写入到 redis 中
	 */
	public static String createCustomerJWT(String customerId, String role) {
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

		long nowMillis = System.currentTimeMillis();
		Date now = new Date(nowMillis);

		//生成签名密钥
		byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Secret);
		Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

		//添加构成JWT的参数
		JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
				.claim("role", role)
				.claim("customerId", customerId)
				.signWith(signatureAlgorithm, signingKey);
		//添加Token过期时间
		long expMillis = nowMillis + CustomerKey.token.expireSeconds() * 1000;
		Date exp = new Date(expMillis);
		String s = DateUtil.dateToString(exp);
		log.info("date:" + s);
		builder.setExpiration(exp).setNotBefore(now);
		//添加token在redis中
		staticRedisService.set(CustomerKey.token, customerId, builder.compact());
		//生成JWT
		return builder.compact();
	}
}